<?php
declare (strict_types = 1);

namespace app\Api\controller;

use app\validate\Examiner as ExaminerValidate;
use think\Exception;
use think\facade\Db;
use think\Request;
use think\Response;

class Examiner
{
    const TABLE_NAME = "examiner";
    protected ExaminerValidate $validate;
    public function __construct(){
        $this->validate = new ExaminerValidate();
    }
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(Request $request)
    {
        //
        $params = $request->get();
        $page = (int)$params['pageNum'];
        $pageSize = (int)$params['pageSize'];
        $cache = $request->cache;
        $query=Db::name(self::TABLE_NAME);
        if(isset($params['name'])&&!empty($params['name'])){
            $query->where('name','=',$params['name']);
        }
        if(isset($params['phone'])&&!empty($params['phone'])){
            $query->where('phone','=',$params['phone']);
        }
        if(isset($params['status'])&&!empty($params['status'])){
            $query->where('status','=',$params['status']);
        }
         if(isset($params['exam_major'])&&!empty($params['exam_major'])){
            $query->where('exam_major','=',$params['exam_major']);
        }
        $paginate = $query->paginate(['page' => $page, 'list_rows' => $pageSize]);
        return success([
            'total' => $paginate->total(),
            'list' => $paginate->items(),
            'current_page' => $paginate->currentPage(),
            'last_page' => $paginate->lastPage(),
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create():Response
    {
        $list = Db::name(self::TABLE_NAME)->where(['status'=>1])->field(['id as value','name as label','phone'])->select();
        return success($list);
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request)
    {
        //
        $params = $request->post();
        $cache = $request->cache;
        try{
            if(!$this->validate->check($params)){
                throw new Exception($this->validate->getError(),9001);
            }
            // 查询地区信息
            $area = Db::name('area')->where('code', 'in', $params['area'])->order('level', 'asc')->select()->toArray();

            $insertData = [
                ...$params,
                'province_code' => $area[0]['code'],
                'province' => $area[0]['name'],
                'city_code' => $area[1]['code'],
                'city' => $area[1]['name'],
                'district_code' => $area[2]['code'],
                'district' => $area[2]['name'],
            ];
            unset($insertData['area']);
            $insertResult= Db::name(self::TABLE_NAME)->strict(false)->insert($insertData);
            if(!$insertResult){
                throw new Exception('编辑考官数据失败',9003);
            }else{
                return success();
            }
        }catch (\Exception $e){
            writeLogToDb('编辑考官失败',$cache['id'],1,$e->getMessage());
            return error([],$e->getCode()?:9005,$e->getMessage());
        }

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return Response
     */
    public function read(int $id):Response
    {
        //
        $examinerData = Db::name(self::TABLE_NAME)->find($id);
        return success($examinerData);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
        //
        $params = $request->post();
        $cache = $request->cache;
        try{
            if(!$this->validate->check($params)){
                throw new Exception($this->validate->getError(),9001);
            }
            // 查询地区信息
            $area = Db::name('area')->where('code', 'in', $params['area'])->order('level', 'asc')->select()->toArray();

            $insertData = [
                ...$params,
                'province_code' => $area[0]['code'],
                'province' => $area[0]['name'],
                'city_code' => $area[1]['code'],
                'city' => $area[1]['name'],
                'district_code' => $area[2]['code'],
                'district' => $area[2]['name'],
            ];
            unset($insertData['area']);
            $insertResult= Db::name(self::TABLE_NAME)->strict(false)->save($insertData);
            if(!$insertResult){
                throw new Exception('编辑考官数据失败',9003);
            }else{
                return success();
            }
        }catch (\Exception $e){
            writeLogToDb('编辑考官失败',$cache['id'],1,$e->getMessage());
            return error([],$e->getCode()?:9005,$e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return Response
     */
    public function delete($id)
    {
        //
    }
    public function importData(Request $request){
        ini_set('memory_limit', '512M');
        $cache = $request->cache;
        $file = request()->file('file');
        $params = $request->get();
        $allowedExtensions = ['xls', 'xlsx'];
        $filename = $_FILES['file']['name'];
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        try {
            if (!in_array(strtolower($extension), $allowedExtensions)) {
                throw new Exception('文件格式错误', 9002);
            }
            // 校验是否存在配置
            $filePath = $file->getRealPath();
            // 把表单里面的数据存储入data中
            $data = readExcelToArray($filePath);
            unset($data[0]);

            $area  =Db::name('area')->select()->toArray();
            $areaOptions=convertValueToKey($area,'name');
            $insertData =[];
            foreach ($data as $index=>$item){
                // print_r(extractAddressComponents($item[2]));
                $insertData[]=[
                    'name'=>$item[1],
                    'gender'=>$item[2]=='男'?1:2,
                    'id_card'=>$item[3],
                    'phone'=>$item[4],
                    'school'=>$item[5],
                    'job_title'=>$item[7],
                    'major'=>$item[8],
                    'exam_major'=>$item[9]=='朗诵'?1:2,
                    'work_unit'=>$item[10],
                    'address'=>$item[11],
                ];
            }

            $insertResult = Db::name('examiner')->insertAll($insertData);
            if($insertResult!==false){
                return success([],0,'导入成功');
            }else{
                throw new Exception('导入失败',9002);
            }
        } catch (\Exception $e) {
            writeLogToDb('导入报名信息失败', $cache['id'], 1, ['message' => $e->getMessage(), 'params' => $request->post('active_id')]);
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }
}
